package com.pactera.miyuangroup.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.util.StringUtils;

import java.util.Base64;
import java.util.Date;
import java.util.List;

/**
 * jwt
 *
 * @author Wangwu
 * @create 2018-03-30 下午2:31
 **/
public class JwtUtils {
    private static final String AUTHORIZATION_HEADER_PREFIX = "bearer ";

    /**
     * 私钥
     */
    private static final String PRIVATE_SECRET = "miyuangroup";

    /**
     * 有效期/秒
     */
    private static final long TTLMillis = 3000;

    /**
     * remove 'Bearer ' string
     *
     * @param authorizationHeader
     * @return
     */
    public static String getRawToken(String authorizationHeader) {
        return authorizationHeader.substring(AUTHORIZATION_HEADER_PREFIX.length());
    }

    public static String getTokenHeader(String rawToken) {
        return AUTHORIZATION_HEADER_PREFIX + rawToken;
    }

    public static boolean validate(String authorizationHeader) {
        return StringUtils.hasText(authorizationHeader) && authorizationHeader.startsWith(AUTHORIZATION_HEADER_PREFIX);
    }

    public static String getAuthorizationHeaderPrefix() {
        return AUTHORIZATION_HEADER_PREFIX;
    }

    public static String getAuthorizationPrivateSecret() {
        return PRIVATE_SECRET;
    }

    public static long getAuthorizationTTLMillis() {
        return TTLMillis;
    }

    /**
     * 生成token
     *
     * @param userName
     * @param userId
     * @param roles
     * @return
     */
    public static String createToken(String userName, String userId, List<String> roles) {
        try {
            SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS512;
            long nowMillis = System.currentTimeMillis();
            Date now = new Date(nowMillis);
            //添加构成JWT的参数
            JwtBuilder builder = Jwts.builder()
                    .claim("role", roles)
                    .claim("userid", userId)
                    .setSubject(userName)//用户名
                    .signWith(SignatureAlgorithm.HS512, JwtUtils.getAuthorizationPrivateSecret());
            //添加Token过期时间
            if (TTLMillis >= 0) {
                long expMillis = nowMillis + (TTLMillis * 1000);
                Date exp = new Date(expMillis);
                builder.setExpiration(exp).setNotBefore(now);
            }
            //生成JWT
            String token = builder.compact();
            token = Base64.getEncoder().encodeToString(JwtUtils.getTokenHeader(token).getBytes("utf-8"));
            return token;
        } catch (Exception e) {
            return null;
        }

    }

    /**
     * 生成token
     *
     * @param userName
     * @param userId
     * @param ttl 有效时间
     * @param roles
     * @return
     */
    public static String createToken(String userName, String userId,long ttl, List<String> roles) {
        try {
            SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS512;
            long nowMillis = System.currentTimeMillis();
            Date now = new Date(nowMillis);
            //添加构成JWT的参数
            JwtBuilder builder = Jwts.builder()
                    .claim("role", roles)
                    .claim("userid", userId)
                    .setSubject(userName)//用户名
                    .signWith(SignatureAlgorithm.HS512, JwtUtils.getAuthorizationPrivateSecret());
            //添加Token过期时间
            if (ttl >= 0) {
                long expMillis = nowMillis + (ttl * 1000);
                Date exp = new Date(expMillis);
                builder.setExpiration(exp).setNotBefore(now);
            }
            //生成JWT
            String token = builder.compact();
            token = Base64.getEncoder().encodeToString(JwtUtils.getTokenHeader(token).getBytes("utf-8"));
            return token;
        } catch (Exception e) {
            return null;
        }

    }

    /**
     * 获取tokenID
     *
     * @param token
     * @return
     */
    public static String getJwtById(String token) {
        try {
            Claims cms = Jwts.parser()
                    .setSigningKey(JwtUtils.getAuthorizationPrivateSecret())
                    .parseClaimsJws(token)
                    .getBody();
            return cms.get("userid", String.class);
        } catch (Exception e) {
            return null;
        }
    }
}
